<?php

require "../utility.php";

$conn = connect_mysql();
$user_id = getUserIdBySessionId($conn);

http_response_code(403);

if ($user_id !== null &&
    check_keys($_GET, "id")) {
    $id = $_GET["id"];
    // 检查这张订单是否是该用户的
    $query_str = "SELECT 1 FROM Orders WHERE ID = '$id' AND userID = $user_id;";
    $query = $conn->query($query_str);
    $result = $query->fetch_row();
    if ($result === null || $result === false) {
        return false;
    }
    $query->close();
    // 如果找到就开始事务
    $conn->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
    $order_book_delete_str = "DELETE FROM OrderBooks WHERE orderID = ?;";
    $order_book_delete_stmt = $conn->prepare($order_book_delete_str);
    $order_book_delete_stmt->bind_param("s", $id);

    if ($order_book_delete_stmt->execute()) {
        $order_delete_str = "DELETE FROM Orders WHERE ID = ?;";
        $order_delete_stmt = $conn->prepare($order_delete_str);
        $order_delete_stmt->bind_param("s", $id);
        if ($order_delete_stmt->execute()) {
            if ($conn->commit()) {
                http_response_code(200);
            }
        } else {
            $conn->rollback();
        }
    } else {
        $conn->rollback();
    }

}

?>